package drb.deploy;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DeployDatabase {
	
	public static void main(String[] args) throws IOException {
		
		System.out.println("TrainManager database deployment");
		
		Properties properties = new Properties();
		properties.load(new FileReader("config/database.properties"));
		
		String database = properties.getProperty("database.name");
		String hostname = properties.getProperty("database.host");
		String username = properties.getProperty("database.username");
		String password = properties.getProperty("database.password");
		
		String deploySQL = readDeploySQL();
		
		try {
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			
			String url = "jdbc:mysql://" + hostname + ":3306/" + database
            + "?user=" + username + "&password=" + password + "&allowMultiQueries=true";
			
			Connection connection = DriverManager.getConnection(url);
			
			connection.setAutoCommit(false);
			
			connection.createStatement().execute(deploySQL);
			
			connection.commit();
			
			System.out.println("OK");
			
		} catch (SQLException ex) {
			System.err.println("Could not deploy");
			ex.printStackTrace();
		}
	}
	
	/**
	 * Reads the contents of the deploy.sql file.
	 */
	private static String readDeploySQL() throws IOException {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader("config/deploy.sql"));
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line + "\r\n");
			}
			return builder.toString();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
	}
	
}
